package com.pro01.backend.controller;

import com.pro01.backend.constants.LotteryPrize;
import com.pro01.backend.pojo.LotteryLog;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.service.LotteryService;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/points/lottery")
public class LotteryController {

    @Autowired
    private LotteryService lotteryService;

    // 抽奖
    @PostMapping
    public Result<LotteryPrize> doLottery(HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            LotteryPrize prize = lotteryService.doLottery(userId);
            return Result.success(prize);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("抽奖失败：" + e.getMessage());
        }
    }

    // 用户查看抽奖记录
    @GetMapping("/logs")
    public Result<PageResult<LotteryLog>> getUserLotteryLogs(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        try {
            Long userId = TokenUtil.getUserId(request);
            PageResult<LotteryLog> pageResult = lotteryService.getUserLotteryLogs(userId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询抽奖记录失败：" + e.getMessage());
        }
    }

    // 用户查看当前剩余积分
    @GetMapping("/remaining")
    public Result<Integer> getRemainingPoints(HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            int points = lotteryService.getCurrentUserPoints(userId);
            return Result.success(points);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询剩余积分失败：" + e.getMessage());
        }
    }

}
